package gui.clientes;

import bin.clientes.Cliente;
import bin.exc.ECadastroInvalido;
import gui.JanelaPrincipal;
import gui.clientes.PainelCadastroClientes;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

public class JanelaCadastroCliente extends javax.swing.JInternalFrame {

    //Atributos
    private JanelaPrincipal janelaPrincipal;
    private JButton[] arrayButtons;
    private PainelCadastroClientes pnlCadastroClientes;
    
    //Indicadores para verificar se a ação é edição ou novo cadastro
    boolean novoCadastro = false;
    boolean fecharJanela = true;

    //Construtor
    public JanelaCadastroCliente(JanelaPrincipal janelaPrincipal) {
        this.janelaPrincipal = janelaPrincipal;
        
        initComponents();
        
        this.arrayButtons = new JButton[]{this.btNovo, this.btEditar, this.btCancelar, this.btConcluir};
        this.setDialogButtons(false);
        this.atualizarTabela();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        btConcluir = new javax.swing.JButton();
        btNovo = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();
        btEditar = new javax.swing.JButton();
        pnlCadastro = new javax.swing.JPanel();
        pnTabela = new javax.swing.JScrollPane();
        tbClientes = new javax.swing.JTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        menuFechar = new javax.swing.JMenu();

        setIconifiable(true);
        setTitle("Cadastro de Clientes");

        btConcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btConcluir.png"))); // NOI18N
        btConcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConcluirActionPerformed(evt);
            }
        });

        btNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btNovo.png"))); // NOI18N
        btNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoActionPerformed(evt);
            }
        });

        btCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btCancelar.png"))); // NOI18N
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });

        btEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btEditar.png"))); // NOI18N
        btEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEditarActionPerformed(evt);
            }
        });

        tbClientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Nome", "Cidade", "Estado", "Pais", "Tipo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbClientes.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        tbClientes.setShowHorizontalLines(false);
        tbClientes.getTableHeader().setReorderingAllowed(false);
        pnTabela.setViewportView(tbClientes);

        javax.swing.GroupLayout pnlCadastroLayout = new javax.swing.GroupLayout(pnlCadastro);
        pnlCadastro.setLayout(pnlCadastroLayout);
        pnlCadastroLayout.setHorizontalGroup(
            pnlCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnTabela, javax.swing.GroupLayout.DEFAULT_SIZE, 633, Short.MAX_VALUE)
        );
        pnlCadastroLayout.setVerticalGroup(
            pnlCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnTabela, javax.swing.GroupLayout.DEFAULT_SIZE, 318, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(btNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btConcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(pnlCadastro, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btConcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 7, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlCadastro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        menuFechar.setText("Fechar");
        menuFechar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuFecharMouseClicked(evt);
            }
        });
        jMenuBar1.add(menuFechar);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //Criar painel para cadastro/edição de clientes
    public void criarPainelDeCadastro(boolean novoCadastro, Cliente clienteEdicao)
    {
        PainelCadastroClientes painelCadastroClientes = new PainelCadastroClientes(this.janelaPrincipal.getArmazem());
        painelCadastroClientes.setSize(632,315);
        this.pnlCadastroClientes = painelCadastroClientes;
        this.pnTabela.setVisible(false);
        this.pnlCadastro.add(painelCadastroClientes);
        this.repaint();
        this.revalidate();
        
        if(!novoCadastro)
        {
            painelCadastroClientes.editarCliente(clienteEdicao);
        }
        this.novoCadastro = novoCadastro;
        
        this.setDialogButtons(true);
        painelCadastroClientes.focoCompPadrao();
    }
    
    //Novo Registro
    private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoActionPerformed
        
        this.criarPainelDeCadastro(true, null);
        this.menuFechar.setEnabled(false);
    }//GEN-LAST:event_btNovoActionPerformed

    //Botão Concluir (Concluir Cadastro ou edição e atualizar tabela)
    private void btConcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConcluirActionPerformed
        
        try 
        {
            if(this.novoCadastro)
            {
                this.pnlCadastroClientes.concluirCadastro();
            }
            else
            {
                this.pnlCadastroClientes.concluirEdicao();
            }
            
            this.pnlCadastroClientes.setVisible(false);
            this.pnTabela.setVisible(true);
            this.setDialogButtons(false);
            this.novoCadastro = false;
            this.menuFechar.setEnabled(true);
            this.atualizarTabela();
            this.janelaPrincipal.armazemNotify();
        } 
        catch (ECadastroInvalido ex) 
        {
            JOptionPane.showMessageDialog(this, "Cliente deve possuir um nome.","Erro",JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btConcluirActionPerformed

    //Botão Cancelar
    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed

        int opcao = JOptionPane.showConfirmDialog(this, "Deseja mesmo cancelar?","Confirmação",JOptionPane.YES_NO_OPTION);
        if(opcao == JOptionPane.YES_OPTION)
        {
            this.pnlCadastroClientes.setVisible(false);
            this.pnTabela.setVisible(true);
            this.setDialogButtons(false);
            this.novoCadastro = false;
            this.menuFechar.setEnabled(true);
        }
    }//GEN-LAST:event_btCancelarActionPerformed

    //Botão Editar
    private void btEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEditarActionPerformed
        
        if(this.tbClientes.getSelectedRow() == -1)
        {
            JOptionPane.showMessageDialog(this, "Nenhum cliente selecionado na tabela.","Edição",JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        Cliente clienteEdicao = null;
        int idCliente = (int)this.tbClientes.getValueAt(this.tbClientes.getSelectedRow(), 0);

        for(Cliente c : this.janelaPrincipal.getArmazem().getListaClientes())
        {
            if(c.getId() == (int)(idCliente))
            {
                clienteEdicao = c;
                break;
            }
        }
        
        this.criarPainelDeCadastro(false, clienteEdicao);
        this.menuFechar.setEnabled(false);
    }//GEN-LAST:event_btEditarActionPerformed

    //Botão Fechar
    private void menuFecharMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuFecharMouseClicked
       
       if(this.menuFechar.isEnabled())
       {
           this.janelaPrincipal.getJanelaFactory().liberarJanela("[Menu, Cadastro, Cliente]");
           this.dispose();
       }
    }//GEN-LAST:event_menuFecharMouseClicked

    //Popular tabela principal
    public void atualizarTabela()
    {
        DefaultTableModel dtm = (DefaultTableModel)this.tbClientes.getModel();
        
        //Remover todos os dados da tabela
        while(dtm.getRowCount() != 0)
        {
            dtm.removeRow(0);
        }
        
        //Popular tabela
        for(Cliente c : this.janelaPrincipal.getArmazem().getListaClientes())
        {
            String fisicoJuridico = c.isFisico() ? "Fisico" : "Juridico";
            Object[] listaClientes = new Object[]{c.getId(), c.getNome(), c.getCidade(), c.getEstado(), c.getPais(), fisicoJuridico};
            dtm.addRow(listaClientes);
        }
    }
    
    //Integracao Botões
    public void setDialogButtons(boolean enable)
    {
        this.arrayButtons[0].setEnabled(!enable);
        this.arrayButtons[1].setEnabled(!enable);
        this.arrayButtons[2].setEnabled(enable);
        this.arrayButtons[3].setEnabled(enable); 
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btConcluir;
    private javax.swing.JButton btEditar;
    private javax.swing.JButton btNovo;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JMenu menuFechar;
    private javax.swing.JScrollPane pnTabela;
    private javax.swing.JPanel pnlCadastro;
    private javax.swing.JTable tbClientes;
    // End of variables declaration//GEN-END:variables
}
